package git.soulbgm.common.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import git.soulbgm.common.message.DecryptHttpInputMessage;
import git.soulbgm.config.KeyConfig;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

import static git.soulbgm.config.KeyConfig.HEADER_CK;

/**
 * 加密请求
 *
 * @author SoulBGM
 * @date 2023-10-08
 */
@ControllerAdvice(basePackages = {"git.soulbgm.controller"})
public class EncryptRequestAdvice implements RequestBodyAdvice {

    private final boolean decrypt;
    private final String uniqueKey;
    private final ObjectMapper mapper;

    public EncryptRequestAdvice(ObjectMapper mapper, KeyConfig config) {
        this.decrypt = config.isDecrypt();
        this.uniqueKey = config.getUniqueKey();
        this.mapper = mapper;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return decrypt;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        String ck = inputMessage.getHeaders().getFirst(HEADER_CK);
        if (uniqueKey.equals(ck)) {
            return inputMessage;
        }
        if (decrypt) {
            return new DecryptHttpInputMessage(inputMessage, mapper, uniqueKey);
        }
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
